﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace huqiang.FileTool
{
    public class VariableStream : System.IO.Stream
    {
        public override bool CanRead => true;

        public override bool CanSeek => true;

        public override bool CanWrite =>false;

        public override long Length => len;

        public override long Position { get => pos; set => pos = value; }

        public override void Flush()
        {
           
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (fileInfo == null)
                return 0;
            long os = fileInfo.dataOffset + pos + fileInfo.keyLen + 8;
            virtualStream.Seek(os, SeekOrigin.Begin);
            return virtualStream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            pos = offset;
            return pos;
        }

        public override void SetLength(long value)
        {
            
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
           
        }
        private VariableStream()
        {
        }
        VirtualStream virtualStream;
        public VariableStream(VirtualStream stream)
        {
#if DEBUG
            if (stream == null)
                throw new Exception("虚拟流文件不能为空!");
#endif
            virtualStream = stream;
        }
        public VariableStream(VirtualStream stream,string key)
        {
#if DEBUG
            if (stream == null)
                throw new Exception("虚拟流文件不能为空!");
#endif
            virtualStream = stream;
            ChangeKey(key);
        }
        long len;
        long pos;
        VirtualFileInfo fileInfo;
        public void ChangeKey(string key)
        {
           fileInfo = virtualStream.Find(key);
        }
    }
}
